﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using GameCore;

namespace GameLogic
{
	public class PanelManager:Singleton<PanelManager>
    {
        /// <summary>
        /// 排序间隔
        /// </summary>
        private const int ORDER_SPACE = 100;

        private Canvas canvas;

        public Canvas Canvas
        {
            get
            {
                return canvas;
            }
        }
        private CanvasScaler canvasScaler;
        private GraphicRaycaster graphicRaycaster;

        private Vector2 DefaultPivot = new Vector2(0.5f,0.5f);
        
        private Transform mrgRoot;
        
        private Transform uiRoot;
        private Transform MaxHighUINode;


        //面板信息管理保存
        private Dictionary<string, Panel> panelDataSave = new Dictionary<string, Panel>();

        public string[] _preLoadPanel;
        public float Progress { private set; get; }

        public void Init()
        {
            //创建UIRoot
            GameObject perfab = App.ResMgr.LoadAsset<GameObject>("UIRoot");
            //App.ResourceMgr.RemoveAsset("UIRoot");
            mrgRoot = Object.Instantiate(perfab).transform.Find("UIRoot");
            mrgRoot.name = "UIRoot";
            //获取Canvas节点
            canvas = mrgRoot.GetComponent<Canvas>();
            canvasScaler = mrgRoot.GetComponent<CanvasScaler>();
            graphicRaycaster = mrgRoot.GetComponent<GraphicRaycaster>();

            //获取UI父节点
            uiRoot = mrgRoot.Find("UINode");

            //获取最高层级UI父节点
            MaxHighUINode = mrgRoot.Find("MaxHighUINode");
        }

        #region 加载面板并初始化UIPanelData
       

        //同步加载UI
        public Panel LoadPanel(string panelName)
        {
            Panel view = null;
            panelDataSave.TryGetValue(panelName, out view);
            if (view != null)
                return view;

            var obj = App.ResMgr.LoadAsset<GameObject>(panelName);
          //  App.ResourceMgr.RemoveAsset(panelName);

            if (obj == null)
                return null;
            //UnityEngine.Profiling.Profiler.BeginSample("InstantiatePanel:"+ panelName);
            var go = Object.Instantiate(obj);
            go.name = panelName;
            view = InitPanelData(go);
            //UnityEngine.Profiling.Profiler.EndSample();
            return view;
        }

               
        /// <summary>
        /// 初始化面板
        /// </summary>
        /// <param name="panelObj"></param>
        /// <returns></returns>
        private Panel InitPanelData(GameObject panelObj)
        {
            var view = panelObj.GetComponent<Panel>();
            if (view == null)
                view = panelObj.AddComponent<Panel>();
            panelObj.SetActive(false);
            //初始化rectTransform
            var rectTransform = panelObj.GetComponent<RectTransform>();
            rectTransform.SetParent(uiRoot);
            rectTransform.anchorMin = Vector2.zero;
            rectTransform.anchorMax = Vector2.one;
            rectTransform.pivot = DefaultPivot;
            rectTransform.localScale = Vector3.one;
            rectTransform.anchoredPosition3D = Vector3.zero;
            rectTransform.sizeDelta = Vector2.zero;
            panelDataSave.Add(panelObj.name, view);
            return view;
        }
        #endregion

        #region 外部调用接口

        /// <summary>
        /// 关闭所有面板,保留主面板和公告面板
        /// </summary>
        public void CloseAllPanelSaveMainPanel(bool isDestroy = false)
        {
            foreach (var view in panelDataSave.Values)
            {
                //存入关闭销毁字典
                if (isDestroy)
                {
                    Object.Destroy(view.gameObject);
                    panelDataSave.Remove(view.name);
                    continue;
                }
                if (!view.gameObject.activeSelf)
                    continue;

                //关闭面板
                view.Close();
            }
        }

        /// <summary>
        /// 打开窗口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T OpenPanel<T>()where T: Panel {
            string panelName = typeof(T).Name;
            Panel view = LoadPanel(panelName);
            if (view.gameObject.activeSelf)
                return view as T;
            view.Open();
            view.transform.SetAsLastSibling();
            ResetPanelSortingOrder();
            return view as T;
        }

        /// <summary>
        /// 打开固定层级窗口
        /// </summary>
        /// <typeparam name="T">窗口类型</typeparam>
        /// <param name="sortingOrder">渲染层级</param>
        /// <returns></returns>
        public T OpenPanel<T>(int sortingOrder) where T : Panel
        {
            string panelName = typeof(T).Name;
            Panel view = LoadPanel(panelName);
            if (view.gameObject.activeSelf)
                return view as T;
            view.Open();
            view.transform.SetAsLastSibling();
            view.transform.SetParent(MaxHighUINode);
            view.SetSortingOrder(sortingOrder);
            return view as T;
        }

        /// <summary>
        /// 重置动态层级窗口的排序
        /// </summary>
        public void ResetPanelSortingOrder() {
            for (int i = 0; i < uiRoot.childCount; i++) {
                uiRoot.GetChild(i).GetComponent<Panel>().SetSortingOrder(i * ORDER_SPACE);
            }
        }

        /// <summary>
        // 关闭面板
        /// </summary>
        public void ClosePanel<T>(bool isDestroy = false)
        {
            string panelName = typeof(T).Name;
            ClosePanel(panelName,isDestroy);
        }


        /// <summary>
        // 关闭面板
        /// </summary>
        public void ClosePanel(string panelName,bool isDestroy = false)
        {
            Panel view = null;
            panelDataSave.TryGetValue(panelName, out view);
            if (view == null)
                return;
            ////获取面板
            //View view = LoadPanel(panelName);

            if (isDestroy == false && view.gameObject.activeSelf == false)
                return;
            //关闭面板
            view.Close();
            if (isDestroy)
            {
                Object.Destroy(view.gameObject);
                panelDataSave.Remove(view.name);
            }
        }




        /// <summary>
        /// 获取面板
        /// </summary>
        public T GetPanel<T>() where T :Panel
        {
            string panelName = typeof(T).Name;
            if (panelDataSave.ContainsKey(panelName))
            {
                return panelDataSave[panelName] as T;
            }
            else
            {
                return null;
            }
        }

        #endregion

    }

}
